<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Common\Tools\RequestTools;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Route;
use UtilBox\LaravelUtils\ApiException;

class WxRouteController extends Controller
{
    public function rewrite(Request $request)
    {
        dd($request->all());
        $route   = $request->get('route');
        throw_if(empty($route), new ApiException('route参数为空', 400));

        $realUrl   = str_replace('-', '/', $route);
        $route     = collect(Route::getRoutes()->getRoutes())->where('uri', $realUrl)->first();
        $routeArr  = explode('@', $route->action['controller']);

        $cls      = app($routeArr[0]);
        $function = $routeArr[1];

        return $cls->$function($request);
    }

    /**
     * 将用户输入的方法转成请求其它服务.
     *
     * @param Request $request
     *
     * @return JsonResponse
     *
     * @throws \Throwable
     */
    public function rewriteBack(Request $request)
    {
        $method  = $request->method(); // 获取请求方法（GET, POST, PUT, DELETE 等）
        $route   = $request->get('route');
        throw_if(empty($route), new ApiException('route参数为空', 400));

        $routeInfo = explode('-', $route);
        $realUrl   = config('wechat.wx_rewrite_api') . '/' . $routeInfo[0] . (!empty($routeInfo[1]) ? '/' . $routeInfo[1] : '');
        $data      = RequestTools::make()->request($method, $realUrl, $request->all());
        Log::info('rewrite_info', [
            'method'  => $method,
            'route'   => $route,
            'realUrl' => $realUrl,
            'data'    => $data,
        ]);

        return response()->json($data, 200, [], JSON_UNESCAPED_UNICODE);
    }
}
